package com.bbcloud.service.impl;

import com.bbcloud.common.Const;
import com.bbcloud.common.ServerResponse;
import com.bbcloud.common.TokenCache;
import com.bbcloud.common.ValidCodeCache;
import com.bbcloud.dao.UserMapper;
import com.bbcloud.pojo.User;
import com.bbcloud.service.IUserService;
import com.bbcloud.util.EmailUtil;
import com.bbcloud.util.MD5Util;
import com.bbcloud.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;

/**
 * Created by liuzhu on 2018/11/2.
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService{


    @Autowired
    private UserMapper userMapper;
    @Override
    public ServerResponse<UserVo> login(String username, String password) {
        int resultCount = userMapper.checkUsername(username);
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("Username does not exist!");
        }
        String md5Password = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username,md5Password);
        if (user == null){
            return ServerResponse.createByErrorMessage("password is wrong!");
        }
        user.setPassword(StringUtils.EMPTY);
        String forgetToken = UUID.randomUUID().toString();
        TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
        UserVo userVo = new UserVo();
        userVo.setUser(user);
        userVo.setToken(forgetToken);
        return ServerResponse.createBySuccess("login success!",userVo);
    }

    public ServerResponse getValidCode(String username){
        int count = (int)((Math.random()*9+1)*100000);
        String validCode = String.valueOf(count);
        ValidCodeCache.setKey(ValidCodeCache.VALID_PREFIX+username,validCode);
        EmailUtil.sample(username,validCode);
        return ServerResponse.createBySuccess();
    }

    public ServerResponse register(String username, String validCode, String password, String repassword) {
        int resultCount = userMapper.checkUsername(username);
        if (resultCount>0){
            return ServerResponse.createByErrorMessage("用户已存在");
        }
        String valid = ValidCodeCache.getKey(ValidCodeCache.VALID_PREFIX+username);
        if (org.apache.commons.lang3.StringUtils.isBlank(valid)){
            return ServerResponse.createByErrorMessage("valid无效或者过期");
        }
        if (org.apache.commons.lang3.StringUtils.equals(validCode,valid)){
            User user = new User();
            user.setRole(Const.Role.ROLE_CUSTOMER);
            user.setUsername(username);
            user.setPassword(MD5Util.MD5EncodeUtf8(password));
            int rowCount = userMapper.insert(user);
            if (rowCount == 0){
                return ServerResponse.createByErrorMessage("注册失败");
            }
            return ServerResponse.createBySuccessMessage("注册成功");
        }else {
            return ServerResponse.createByErrorMessage("valid错误,请重新获取");
        }
    }

    public ServerResponse<User>getUserInfo(String username,String token){
        int resultCount = userMapper.checkUsername(username);
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("Username does not exist!");
        }
        String tokenValid = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
        if (org.apache.commons.lang3.StringUtils.equals(tokenValid,token)){
            //todo 查询用户信息
            User user = userMapper.getUserInfo(username);
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("Please log in again");
    }

    public ServerResponse<String> forgetResetPassword(String username,String password,String validCode){
        int resultCount = userMapper.checkUsername(username);
        if (resultCount<=0){
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String valid = ValidCodeCache.getKey(ValidCodeCache.VALID_PREFIX+username);
        if (org.apache.commons.lang3.StringUtils.isBlank(valid)){
            return ServerResponse.createByErrorMessage("valid无效或者过期");
        }
        if (org.apache.commons.lang3.StringUtils.equals(validCode,valid)){
            String md5Password = MD5Util.MD5EncodeUtf8(password);
            int rowCount = userMapper.updatePasswordByUsername(username,md5Password);
            if (rowCount>0){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        }else {
            return ServerResponse.createByErrorMessage("valid错误,请重新获取");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
    }
}
